package com.kk.score.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import com.kk.score.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.kk.score.entity.ReportEntity;
import com.kk.score.service.ReportService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author KK
 * @email 409592048@qq.com
 * @date 2022-11-02 12:28:00
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private FileUtils fileUtils;

    /**
     * 列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = reportService.queryPage(params);

        return R.ok().put("data", page);
    }

    /**
     * 上传报告
     */
    @PostMapping("/uploadPdf")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public R uploadPdf(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "uid") String uid, @RequestParam(value = "year") String year, HttpServletRequest request) throws Exception {
        //uid为部门的uid
        File file1 = MultiFileUtils.multipartFileToFile(file);
        //由于文件服务器读取中文乱码，文件名改为数字
        String name = System.currentTimeMillis() + ".pdf";
        boolean flag = fileUtils.uploadFile(file1, name);
        if (flag) {
            ReportEntity reportEntity = new ReportEntity(name);
            reportService.save(reportEntity);
            request.getSession().setAttribute(uid + year, reportEntity.getUid());
            request.getSession().setAttribute(name, reportEntity.getUid());
        }
        return R.ok().put("data", flag).put("name", name);
    }

    /**
     * 信息
     */
    @GetMapping("/{uid}")
    public void info(@PathVariable("uid") String uid, HttpServletResponse response) {
        ReportEntity report = reportService.getById(uid);
        try {
            response.setContentType("application/pdf");
            response.getOutputStream().write(fileUtils.getBytesByFile(report.getFileName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
